#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据管理模块
"""

import os
import json
import threading
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
from utils.logger import get_logger


class DataManager:
    """数据管理器"""
    
    def __init__(self):
        self.logger = get_logger(__name__)
        self.lock = threading.Lock()
        
        # 初始化数据
        self.accounts = []
        self.servicers = []
        self.sessions = {}
        self.messages = []
        self.tokens = {}
        self.stats = {
            'total_requests': 0,
            'successful_requests': 0,
            'failed_requests': 0,
            'active_sessions': 0
        }
        
        # 初始化默认数据
        self._init_default_data()
        
        # 加载数据
        self.load_data()
    
    def _init_default_data(self):
        """初始化默认数据"""
        # 默认客服账号
        self.accounts = [
            {
                "open_kfid": "mock_kf_001",
                "name": "Mock客服账号",
                "status": 1
            },
            {
                "open_kfid": "mock_kf_002",
                "name": "Mock客服账号2",
                "status": 1
            }
        ]
        
        # 默认客服人员
        self.servicers = [
            {
                "userid": "mock_servicer_001",
                "name": "Mock客服1",
                "status": 1,
                "status_time": int(datetime.now().timestamp())
            },
            {
                "userid": "mock_servicer_002",
                "name": "Mock客服2",
                "status": 1,
                "status_time": int(datetime.now().timestamp())
            }
        ]
        
        # 默认会话
        self.sessions = {
            "mock_user_001": {
                "external_userid": "mock_user_001",
                "open_kfid": "mock_kf_001",
                "service_state": 1,
                "servicer_userid": "mock_servicer_001",
                "create_time": int(datetime.now().timestamp())
            }
        }
        
        # 默认消息
        self.messages = [
            {
                "msgid": "mock_msg_001",
                "open_kfid": "mock_kf_001",
                "external_userid": "mock_user_001",
                "send_time": int(datetime.now().timestamp()),
                "msgtype": "text",
                "text": {
                    "content": "你好，我需要帮助"
                }
            }
        ]
    
    def load_data(self):
        """从文件加载数据"""
        data_file = os.getenv('MOCK_DATA_FILE_PATH', './mock_data.json')
        if os.path.exists(data_file):
            try:
                with open(data_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.accounts = data.get('accounts', self.accounts)
                    self.servicers = data.get('servicers', self.servicers)
                    self.sessions = data.get('sessions', self.sessions)
                    self.messages = data.get('messages', self.messages)
                    self.tokens = data.get('tokens', self.tokens)
                    self.stats = data.get('stats', self.stats)
                self.logger.info(f"从文件加载数据成功: {data_file}")
            except Exception as e:
                self.logger.error(f"加载数据文件失败: {e}")
    
    def save_data(self):
        """保存数据到文件"""
        data_file = os.getenv('MOCK_DATA_FILE_PATH', './mock_data.json')
        try:
            data = {
                'accounts': self.accounts,
                'servicers': self.servicers,
                'sessions': self.sessions,
                'messages': self.messages,
                'tokens': self.tokens,
                'stats': self.stats
            }
            with open(data_file, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            self.logger.info(f"数据保存成功: {data_file}")
        except Exception as e:
            self.logger.error(f"保存数据文件失败: {e}")
    
    def get_accounts(self) -> List[Dict[str, Any]]:
        """获取客服账号列表"""
        with self.lock:
            return self.accounts.copy()
    
    def get_servicers(self, open_kfid: str) -> List[Dict[str, Any]]:
        """获取客服人员列表"""
        with self.lock:
            return [s for s in self.servicers if s.get('open_kfid') == open_kfid]
    
    def get_session(self, external_userid: str, open_kfid: str, update_activity: bool = False) -> Optional[Dict[str, Any]]:
        """获取会话状态 - 带3分钟超时检查"""
        with self.lock:
            key = f"{external_userid}_{open_kfid}"
            session = self.sessions.get(key)
            
            if session:
                # 检查会话是否超时（3分钟）
                current_time = int(datetime.now().timestamp())
                last_update_time = session.get('update_time', session.get('create_time', 0))
                timeout_seconds = 3 * 60  # 3分钟
                
                if current_time - last_update_time > timeout_seconds:
                    # 会话超时，删除旧会话
                    timeout_duration = current_time - last_update_time
                    self.logger.info(f"会话超时，删除旧会话 - 用户: {external_userid}, "
                                    f"客服: {open_kfid}, 超时时间: {timeout_duration}秒")
                    del self.sessions[key]
                    self.save_data()
                    return None
                else:
                    # 会话未超时，只在需要时更新最后活动时间
                    if update_activity:
                        session['update_time'] = current_time
                        self.sessions[key] = session
                        self.save_data()
                    
                    remaining_time = timeout_seconds - (current_time - last_update_time)
                    self.logger.info(f"会话活跃 - 用户: {external_userid}, "
                                    f"客服: {open_kfid}, 剩余时间: {remaining_time}秒")
            
            return session
    
    def update_session(self, external_userid: str, open_kfid: str, session_data: Dict[str, Any]):
        """更新会话状态"""
        with self.lock:
            key = f"{external_userid}_{open_kfid}"
            self.sessions[key] = session_data
            self.save_data()
    
    def add_message(self, message: Dict[str, Any]):
        """添加消息"""
        with self.lock:
            self.messages.append(message)
            self.save_data()
            
            # 记录醒目的消息内容日志
            msg_type = message.get('msgtype', 'unknown')
            direction = message.get('direction', 'unknown')
            external_userid = message.get('external_userid', 'unknown')
            
            # 根据消息类型提取内容
            content = "无内容"
            if msg_type == "text" and "text" in message:
                content = message["text"].get("content", "无内容")
            elif msg_type == "image" and "image" in message:
                content = f"图片消息: {message['image'].get('media_id', '无ID')}"
            elif msg_type == "voice" and "voice" in message:
                content = f"语音消息: {message['voice'].get('media_id', '无ID')}"
            elif msg_type == "file" and "file" in message:
                content = f"文件消息: {message['file'].get('media_id', '无ID')}"
            elif msg_type == "link" and "link" in message:
                content = f"链接消息: {message['link'].get('url', '无URL')}"
            
            # 使用醒目的格式记录消息
            self.logger.info("=" * 60)
            self.logger.info(f"📨 新消息 [{direction.upper()}] - 类型: {msg_type.upper()}")
            self.logger.info(f"👤 用户: {external_userid}")
            self.logger.info(f"💬 内容: {content}")
            self.logger.info("=" * 60)
    
    def get_messages(self, cursor: str = None, limit: int = 1000) -> Dict[str, Any]:
        """获取消息列表"""
        with self.lock:
            # 简单的游标实现
            start_index = 0
            if cursor:
                try:
                    start_index = int(cursor)
                except ValueError:
                    start_index = 0
            
            end_index = min(start_index + limit, len(self.messages))
            msg_list = self.messages[start_index:end_index]
            
            has_more = 1 if end_index < len(self.messages) else 0
            next_cursor = str(end_index) if has_more else ""
            
            return {
                "next_cursor": next_cursor,
                "has_more": has_more,
                "msg_list": msg_list
            }
    
    def get_messages_by_user(self, user_id: str) -> List[Dict[str, Any]]:
        """根据用户ID获取消息列表"""
        with self.lock:
            user_messages = []
            for message in self.messages:
                if message.get('external_userid') == user_id:
                    user_messages.append(message)
            
            # 按时间排序（最新的在前）
            user_messages.sort(key=lambda x: x.get('send_time', 0), reverse=True)
            return user_messages
    
    def get_all_sessions(self) -> List[Dict[str, Any]]:
        """获取所有会话列表"""
        with self.lock:
            return list(self.sessions.values())
    
    def get_service_states(self, cursor: str = None, limit: int = 1000) -> Dict[str, Any]:
        """获取会话状态列表"""
        with self.lock:
            session_list = list(self.sessions.values())
            
            # 简单的游标实现
            start_index = 0
            if cursor:
                try:
                    start_index = int(cursor)
                except ValueError:
                    start_index = 0
            
            end_index = min(start_index + limit, len(session_list))
            service_state_list = session_list[start_index:end_index]
            
            has_more = 1 if end_index < len(session_list) else 0
            next_cursor = str(end_index) if has_more else ""
            
            return {
                "next_cursor": next_cursor,
                "has_more": has_more,
                "service_state_list": service_state_list
            }
    
    def create_token(self, corpid: str, corpsecret: str) -> str:
        """创建访问令牌"""
        with self.lock:
            token = f"mock_access_token_{corpid}_{int(datetime.now().timestamp())}"
            expires_in = int(os.getenv('MOCK_TOKEN_EXPIRES', '7200'))
            expire_time = datetime.now() + timedelta(seconds=expires_in)
            
            self.tokens[token] = {
                'corpid': corpid,
                'corpsecret': corpsecret,
                'expire_time': expire_time.isoformat(),
                'expires_in': expires_in
            }
            
            self.save_data()
            return token
    
    def validate_token(self, token: str) -> bool:
        """验证访问令牌"""
        with self.lock:
            if token not in self.tokens:
                return False
            
            token_data = self.tokens[token]
            expire_time = datetime.fromisoformat(token_data['expire_time'])
            
            if datetime.now() > expire_time:
                # 删除过期token
                del self.tokens[token]
                self.save_data()
                return False
            
            return True
    
    def update_stats(self, success: bool = True):
        """更新统计信息"""
        with self.lock:
            self.stats['total_requests'] += 1
            if success:
                self.stats['successful_requests'] += 1
            else:
                self.stats['failed_requests'] += 1
            
            self.stats['active_sessions'] = len(self.sessions)
    
    def get_stats(self) -> Dict[str, Any]:
        """获取统计信息"""
        with self.lock:
            return self.stats.copy()
